<template>
  <div>
    <div style="padding: 15px; border-bottom: 1px solid #ddd">
      <el-upload
          style="display: inline-block; margin-right: 10px"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleFileSuccess"
      >
        <el-button type="primary">上传文件</el-button>
      </el-upload>
      <el-button type="primary" plain @click="addFolder" v-if="category === 'all'">新建文件夹</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <div style="padding: 15px">
      <a style="color: #666" :href="'/manager/diskHome?category=' + category">全部文件 <i class="el-icon-arrow-right" v-if="folders.length"></i></a>
      <a
          style="color: #666"
          :href="'/manager/diskHome?category=' + category + '&folderId=' + item.id"
          v-for="(item, index) in folders"
          :key="item.id"
      >
        {{ item.name }} <i class="el-icon-arrow-right" v-if="index !== folders.length - 1"></i>
      </a>
    </div>

    <div>
      <div>
        <!-- 对话框用于输入文件夹名 -->
        <el-dialog
            v-model="dialogVisible"
            title="新增文件夹"
            width="30%"
            @close="resetForm"
        >
          <el-form :model="form" ref="formRef">
            <el-form-item
                label="文件夹名称"
                prop="name"
                :rules="[{ required: true, message: '请输入文件夹名称' }]"
            >
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd()">确认</el-button>
        </span>
          </template>
        </el-dialog>

        <!-- 树形组件 -->
        <el-tree
            style="max-width: 1000px"
            :data="dataSource"
            show-checkbox
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            ref="treeRef"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span>{{ node.label }}</span>
              <div>
                <el-button type="primary" link @click="append(node, data)">
                  新增文件夹
                </el-button>
                <el-button
                    style="margin-left: 4px"
                    type="danger"
                    link
                    @click="remove(node, data)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed,toRefs,watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElButton } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js";

////tree
//对话框开始
const currentRow = null
const dialogVisible = ref(false)
const formRef = ref(null)
const treeRef = ref(null)
const form = reactive({
  name: ''
})
const folderId=ref(null)
const currentNode = ref(null)
// 打开新增对话框
const append = (node, data) => {
  currentNode.value = node
  dialogVisible.value = true
  folderId.value = node.id
  console.log("folderId.value="+folderId.value)
  uploadUrl.value = 'http://localhost:8888/diskFiles/add?folder=否' +
      (folderId.value ? '&folderId=' + folderId.value : '')
}
//确认添加新文件夹  修改向后端发出请求保存
const confirmAdd = async () => {
  await formRef.value.validate()

  const newNode = {
    id: Date.now(),
    label: form.name,
    children: []
  }

  if (!currentNode.value.data.children) {
    currentNode.value.data.children = []
  }

  //将新创建的文件夹节点添加到当前选中节点的子节点数组中
  currentNode.value.data.children.push(newNode)

  //让树组件自动选中并滚动到新创建的节点
  treeRef.value.setCurrentKey(newNode.id)
  //console.log("@@@@"+folderId.value)
  try {

      const url = `/diskFiles/add?folder=是&name=${form.name}` +
          (folderId.value ? `&folderId=${folderId.value}` : '')
      await request.post(url)

    ElMessage.success("操作成功")
    load()

  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '操作失败')
  }
  dialogVisible.value = false
  form.name = ''

}
//重置表单
const resetForm = () => {
  form.name = ''
  formRef.value.resetFields()
}
// 删除节点
const remove = (node, data) => {
  const parent = node.parent
  const children = parent.data.children || parent.data
  const index = children.findIndex(d => d.id === data.id)
  children.splice(index, 1)
}
//对话框结束


interface Tree {
  id: number
  label: string
  children?: Tree[]
}


// const append = (data: Tree) => {
//   //改为输入，1点击新增后弹出输入框，输入新的文件夹，2.确定 保存触发保存方法
//   const newChild = { id: id++, label: 'testtest', children: [] }
//   if (!data.children) {
//     data.children = []
//   }
//   data.children.push(newChild)
//   dataSource.value = [...dataSource.value]
// }

// const remove = (node: Node, data: Tree) => {
//   const parent = node.parent
//   const children: Tree[] = parent.data.children || parent.data
//   const index = children.findIndex((d) => d.id === data.id)
//   //携带数据向后端发起
//   children.splice(index, 1)
//   dataSource.value = [...dataSource.value]
// }


const dataSource = ref<Tree[]>([])

const fetchFileTree = async () => {
  try {
    const response = await request.get('/diskFiles/getFileTree');
    dataSource.value = response.data.data;
  } catch (error) {
    console.error('获取文件树失败:', error);
  }
};
/////tree

const props = defineProps({
  typeList: Array,
  category: String
})
const {category} = toRefs(props)
const route = useRoute()

// 响应式数据

//const folderId = ref(route.query.folderId)
const tableData = ref([])
const user = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const uploadUrl = ref('')
const ids = ref([])
const folders = ref([])


// 监听 category 变化
watch(() => props.category, (newVal) => {
  load();
});

// 监听 folderId 变化
watch(() => route.query.folderId, (newVal) => {
  folderId.value = newVal;
  load();
});



// 初始化加载
onMounted(() => {
  //fetchFileTree()
  load()
  // uploadUrl.value = 'http://localhost:8888/diskFiles/add?folder=否' +
  //     (folderId.value ? '&folderId=' + folderId.value : '')
})

// 方法
const load = async () => {
  try {
    const response = await request.get('/diskFiles/getFileTree');
    dataSource.value = response.data.data;


    console.log("category.value=="+category.value)
    console.log("folderId.value=="+folderId.value)
    const [filesRes, foldersRes] = await Promise.all([
      request.get('/diskFiles/selectAll',
          {
            params: {
              category: category.value || null,
              folderId: folderId.value || null
            }
          }),
      request.get('/diskFiles/selectFolders', {
        params: { folderId: folderId.value || null }
      })
    ])
    tableData.value = (filesRes.data.data || []).map(item => ({
      ...item,
      optShow: false
    }))
    folders.value = foldersRes.data.data || []
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

const handleFileSuccess = (res) => {
  if (res.code === '0') {
    ElMessage.success("上传成功")
    fetchFileTree()
    load()
  } else {
    ElMessage.error('上传失败')
  }
}

const addFolder = () => {
  tableData.value.unshift({
    name: '',
    type: 'folder',
    unSave: true,
    folderId: folderId.value || null
  })
}

const delBatch = async () => {
  if (!ids.value.length) {
    ElMessage.warning('请选择数据')
    return
  }

  try {
    await ElMessageBox.confirm('您确定批量删除这些数据吗？', '确认删除', { type: "warning" })
    await request.delete('/diskFiles/delete/batch', { data: ids.value })
    ElMessage.success('操作成功')
    load()
  } catch (error) {
    // 取消删除
  }
}


const openFile = (row) => {
  if (row.folder === '是') {
    window.location.href = `/manager/diskHome?category=${category.value}&folderId=${row.id}`
  } else {
    window.open(`http://localhost:8888/diskFiles/preview/${row.id}`)
  }
}

const download = (url) => {
  window.open(url)
}

const mouseEnter = (row) => {
  if (!row.unSave) row.optShow = true
}

const mouseLeave = (row) => {
  if (!row.unSave) row.optShow = false
}


const save = async (row) => {
  try {
    if (row.id) {
      await request.put('/diskFiles/update', row)
    } else {
      const url = `/diskFiles/add?folder=是&name=${row.name}` +
          (folderId.value ? `&folderId=${folderId.value}` : '')
      await request.post(url)
    }
    ElMessage.success("操作成功")
    load()

  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '操作失败')
  }
}

const cancel = (row) => {
  if (row.id) {
    load()
  } else {
    const index = tableData.value.findIndex(item => item === row)
    tableData.value.splice(index, 1)
  }
}

const handleSelectionChange = (rows) => {
  ids.value = rows.map(v => v.id)
}

const del = async (id) => {
  try {
    await ElMessageBox.confirm('您确定删除吗？', '确认删除', { type: "warning" })
    await request.delete(`/diskFiles/trash/${id}`)
    ElMessage.success('操作成功')
    load()
  } catch (error) {
    // 取消删除
  }
}
</script>

<style scoped>
.el-form-item__label {
  padding-right: 50px !important;
}

/*tree*/
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

/*tree*/
</style>